package com.qujia.system.domain.vo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qujia.system.jinkong.GatewayRequest;
import com.qujia.system.jinkong.GatewayResponse;
import com.qujia.system.jinkong.JKPayParam;
import com.saobei.open.sdk.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/***
 * 通联支付工具类
 */
@Slf4j
public class JKPayUtil {

    static String  password="zhyj2022"; //私钥提取密码
//    static String  private_pfxPath="C:\\Users\\zcs\\Desktop\\商户密钥\\私钥.pfx"; //商户私钥地址
//
//    static String public_certPath="C:\\Users\\zcs\\Desktop\\商户密钥\\xdzf_cfca_prd.cer"; //现代支付公钥地址


    static String url = "https://saas.mfe88.com/gateway-scan-pay/api/scanRefund";

    public static HashMap JKPay(JKPayParam jkPayParam){

        GatewayRequest param = new GatewayRequest();
        param.setMerchantNo(jkPayParam.getMerchantNo()); //商户编号
        param.setMerOrderNo(jkPayParam.getOrderNo()); // 商户订单号
        param.setTransCode("getCodeUrl"); // 交易码

        param.setMerSubmitTime(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())); //提交时间
        param.setSignType("3"); // cfca-RSA证书签名
        param.setTransVersion("1.0");
        // 组装 --参考接口文档相关参数
        JSONObject object = new JSONObject();
        object.put("payChannelCode","109"); //微信小程序
        object.put("notifyUrl",jkPayParam.getNotifyUrl()); // 商户接受异步通知地址
        object.put("amount",jkPayParam.getAmt()); //交易金额--单位分
        object.put("openid",jkPayParam.getOpenId()); //微信用户标识
        object.put("appid",jkPayParam.getAppId()); //公众账号ID
        object.put("curType","CNY"); //交易币种--CNY(人民币)
        object.put("commodityName","油品"); //商品信息
        object.put("splitFlag","01"); //商户列表分账
        object.put("orderSource","2"); //订单来源：1PC 2手机
        object.put("merAttach",jkPayParam.getOrderNo()); //商户附加数据，添加为订单号
        object.put("orderTime",new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())); //时间戳：yyyyMMddHHmmss
        System.out.println("请求参数为="+object);
        String msgcip = Base64Util.encode(object.toString());
        param.setMsgCipherText(msgcip);
        try {
            Map<String,Object> sign = Tools.objectToMap(param);
            // 组装签名值
            String content = ParaUtils.createLinkStringObj(ParaUtils.removeMap(sign));
            // 签名
            byte[]msg = CfcaCertUtil.signMessage(content,jkPayParam.getPrivate_pfxPath(),password); //商户自己的私钥签名
            String signValue = new String(msg);
            param.setSignValue(signValue);
            // 发送请求信息
            String rspMsg = HttpClientUtil.post(url, JSONObject.toJSONString(param),3000, "application/json","utf-8");
            System.out.println("返回结果="+rspMsg);
            GatewayResponse gatewayResponse = new ObjectMapper().readValue(rspMsg, GatewayResponse.class);
            if("0000".equals(gatewayResponse.getRespCode())){ // 受理成功
                //验签处理
                Map<String,Object> verifyMap= Tools.objectToMap(gatewayResponse);
                String verifyContent = ParaUtils.createLinkStringObj(ParaUtils.removeMap(verifyMap));
                String signvalue= gatewayResponse.getSignValue();
                // 验签
                boolean checkverify = CfcaCertUtil.verifyValue(verifyContent,signvalue,jkPayParam.getPublic_certPath()); //现代支付公钥
                if(checkverify){ //验签成功
                    String orderInfo = Base64Util.decodeString(gatewayResponse.getOrderInfo());
                    JSONObject orderObj = JSONObject.parseObject(orderInfo);
                    JSONObject orderObj1 = JSONObject.parseObject(orderObj.get("wcPayData")+"");
                    HashMap reqData = new HashMap();
                    reqData.put("payTimeStamp", orderObj1.get("timeStamp"));
                    reqData.put("payPackage", orderObj1.get("package"));
                    reqData.put("paynonceStr", orderObj1.get("nonceStr"));
                    reqData.put("paySignType", orderObj1.get("signType"));
                    reqData.put("paySign", orderObj1.get("paySign"));

                    reqData.put("merchant_name", orderObj.get("merchantNo"));

                    reqData.put("terminal_time", orderObj.get("tradeTime"));

                    reqData.put("code", orderObj.get("resultCode"));
                    reqData.put("merchantsNumber", orderObj.get("mfhcdOrderNo"));
                    System.out.println("返回参数="+reqData);

                    return reqData;

                    // 根据返回结果--商户后续处理。TODO
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new HashMap();

    }

    public static HashMap JKRefund(JKPayParam jkPayParam){

        GatewayRequest param = new GatewayRequest();
        param.setMerchantNo(jkPayParam.getMerchantNo()); //商户编号
        param.setMerOrderNo(jkPayParam.getOrderNo()); // 商户订单号

        param.setMerSubmitTime(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())); //提交时间
        param.setSignType("3"); // cfca-RSA证书签名
        param.setTransVersion("1.0");
        // 组装 --参考接口文档相关参数
        JSONObject object = new JSONObject();

        object.put("orderNo",jkPayParam.getOldOrderNo()); //原交易订单号
        object.put("refundAmount",jkPayParam.getAmt()); //交易金额--单位分
        object.put("curType","CNY"); //交易币种--CNY(人民币)
        object.put("refundTime",new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())); //微信用户标识

        System.out.println("请求参数为="+object);
        String msgcip = Base64Util.encode(object.toString());
        param.setMsgCipherText(msgcip);
        try {
            Map<String,Object> sign = Tools.objectToMap(param);
            // 组装签名值
            String content = ParaUtils.createLinkStringObj(ParaUtils.removeMap(sign));
            // 签名
            byte[]msg = CfcaCertUtil.signMessage(content,jkPayParam.getPrivate_pfxPath(),password); //商户自己的私钥签名
            String signValue = new String(msg);
            param.setSignValue(signValue);
            // 发送请求信息
            String rspMsg = HttpClientUtil.post(url, JSONObject.toJSONString(param),3000, "application/json","utf-8");
            System.out.println("返回结果="+rspMsg);
            GatewayResponse gatewayResponse = new ObjectMapper().readValue(rspMsg, GatewayResponse.class);
            if("0000".equals(gatewayResponse.getRespCode())){ // 受理成功
                //验签处理
                Map<String,Object> verifyMap= Tools.objectToMap(gatewayResponse);
                String verifyContent = ParaUtils.createLinkStringObj(ParaUtils.removeMap(verifyMap));
                String signvalue= gatewayResponse.getSignValue();
                // 验签
                boolean checkverify = CfcaCertUtil.verifyValue(verifyContent,signvalue,jkPayParam.getPublic_certPath()); //现代支付公钥
                if(checkverify){ //验签成功
                    String orderInfo = Base64Util.decodeString(gatewayResponse.getOrderInfo());
                    JSONObject orderObj = JSONObject.parseObject(orderInfo);
                    System.out.println(orderInfo);
                    JSONObject orderObj1 = JSONObject.parseObject(orderObj.get("wcPayData")+"");
                    HashMap reqData = new HashMap();
                    reqData.put("payTimeStamp", orderObj1.get("timeStamp"));
                    reqData.put("payPackage", orderObj1.get("package"));
                    reqData.put("paynonceStr", orderObj1.get("nonceStr"));
                    reqData.put("paySignType", orderObj1.get("signType"));
                    reqData.put("paySign", orderObj1.get("paySign"));

                    reqData.put("merchant_name", orderObj.get("merchantNo"));

                    reqData.put("terminal_time", orderObj.get("tradeTime"));

                    reqData.put("code", orderObj.get("resultCode"));
                    reqData.put("merchantsNumber", orderObj.get("mfhcdOrderNo"));
                    System.out.println("返回参数="+reqData);

                    return reqData;

                    // 根据返回结果--商户后续处理。TODO
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new HashMap();

    }

    /**
     * 从客户端传来的请求流中获得请求参数
     *
     * @param request
     * @return String
     */
    //解析当前请求的数据流
    public static String getParamByStream(HttpServletRequest request) {
        String param = "";
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            StringBuffer sb = new StringBuffer();
            is = request.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            br = new BufferedReader(isr);
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            param = sb.toString();
            param = URLDecoder.decode(param, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return param;

    }




}
